<template>
  <div class="upward">
    <img src="../assets/路径.png" alt="" @click="goback" />
    <span class="text">位置选择</span>
    <div class="area">
      <van-search
        v-model="value"
        placeholder="请输入地区名称查询"
        :show-action="showAction"
        @search="Find"
      ></van-search>
    </div>
  </div>
  <div class="CityRow">
    <!-- 使用分组方法来渲染分类后的城市列表 -->
    <div v-for="(group, index) in groupedCities" :key="index">
      <div>{{ group.letter }}</div>
      <div v-for="city in group.cities" :key="city.name" @click="selectCity(city.name, 'start')">
        {{ city.name }}
      </div>
      <div
        v-for="city in group.cities"
        :key="city.name + '_end'"
        @click="selectCity(city.name, 'end')"
      >
        {{ city.name }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { createSignHeader } from '@/crypto/a1.js'
import { useCityStore } from '@/stores/cityStore.js'
const value = ref('')
const showAction = ref(true)
const router = useRouter()
const CityList = ref([])
const groupedCities = ref([])
const cityStore = useCityStore()

// 分组方法
function groupByLetter(cities) {
  const grouped = {}
  cities.forEach((city) => {
    if (!grouped[city.letter]) {
      grouped[city.letter] = { letter: city.letter, cities: [] }
    }
    grouped[city.letter].cities.push(city)
  })
  return Object.values(grouped)
}

// 新增方法处理 API 调用
async function fetchCityList() {
  const path = '/s/p11/area/citys'
  const params = {
    start_adcode: ''
  }
  const now = Date.now()
  const gmt = new Date(now).toUTCString()
  const header = createSignHeader(path, params, gmt)

  try {
    const response = await axios.post(`https://newapi-test.bbxhc.com${path}`, params, {
      headers: {
        ...header,
        at: 401,
        tm: now,
        av: '202409281550',
        ci: 'bbx24306',
        di: 'ffe882f016e9df3d7c091f936c54c0c6',
        qr: '',
        to: 'bWgPZwAAAAABAJO33qHphHS76iRLHJKDfSUHVbgFbnahqUKbgyftMIMBmMsypmwBreVKbGnMUpQvFElfURuhkYrGJAAAAA=='
      }
    })
    if (response.status === 200) {
      const groupedData = groupByLetter(response.data.result)
      groupedCities.value = groupedData
      CityList.value = response.data.result
    } else {
      const message = response.data.message || '请求异常'
      console.error(message)
    }
  } catch (err) {
    console.error(err)
  }
}

// 筛选城市（搜索方法）
function Find() {
  if (!value.value) {
    groupedCities.value = groupByLetter(CityList.value)
    return
  }

  const filteredCities = CityList.value.filter((city) =>
    city.name.toLowerCase().includes(value.value.toLowerCase())
  )

  groupedCities.value = groupByLetter(filteredCities)
}

// 选择城市
function selectCity(cityName, type) {
  if (type === 'start') {
    cityStore.setStartCity(cityName) // 设置起点城市
    router.push('/startpos')
  } else if (type === 'end') {
    cityStore.setEndCity(cityName) // 设置终点城市
    router.push('/endPot')
  }
}
function goback() {
  router.go(-1)
}
// 页面挂载后调用方法来发送请求
onMounted(fetchCityList)
</script>

<style scoped>
.upward img {
  margin-left: 0.27rem;
  width: 0.19rem;
  height: 0.32rem;
}
.upward {
  width: 7.5rem;
  height: 1.76rem;
}
.text {
  font-weight: 500;
  font-size: 0.34rem;
  text-align: center;
  margin-left: 3.07rem;
}
.CityRow {
  margin-top: 0.7rem;
}
.CityRow div {
  font-size: 0.28rem;
  text-align: left;
  margin-left: 0.2rem;
}
</style>
